package com.huluobo.h3kotlinproject.login

import android.content.Intent
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.h3kotlinproject.net.Const
import com.huluobo.h3kotlinproject.MainActivity
import com.huluobo.h3kotlinproject.R
import com.huluobo.h3kotlinproject.register.RegisterActivity
import com.huluobo.h3kotlinproject.base.BaseMVVMActivity
import com.huluobo.h3kotlinproject.databinding.ActivityLoginBinding
import com.huluobo.h3kotlinproject.db.DatabaseUtil
import com.huluobo.h3kotlinproject.db.entity.Money
import com.huluobo.h3kotlinproject.db.entity.UserInfo

class LoginActivity : BaseMVVMActivity<ActivityLoginBinding>() {

    //延迟初始化viewModel
    private lateinit var viewModel: LoginViewModel
    override fun initData() {
        //构建viewModel,注意不是new的,是通过ViewModelProvider拿到的
        //::class.java kotlin中如果需要调用javaClass,需要加双冒号
        viewModel = ViewModelProvider(this)[LoginViewModel::class.java]

        dataBinding.loginBtn.setOnClickListener {
            viewModel.login(dataBinding.loginUsernameEt.text.toString(), dataBinding.loginPasswordEt.text.toString())
        }

        //观察登录成功的回调
        viewModel.loginSuccess.observe(
            this
        ) {
            if (it.code == 200) {
                ToastUtils.showLong("username:${it.data.username}")
                //保存一下用户的SP
                SPUtils.getInstance().put(Const.SP_TOKEN, it.data.token)
                SPUtils.getInstance().put(Const.SP_USER_ID, it.data.id)

                //把返回的用户信息保存到数据库
                DatabaseUtil.getDefaultDb().userInfoDao().insertUserInfo(
                    UserInfo(
                        it.data.id,
                        it.data.address,
                        it.data.birth,
                        it.data.email,
                        it.data.icon,
                        it.data.nickname,
                        it.data.password,
                        it.data.username
                    )
                )

                //给用户一点儿余额
                DatabaseUtil.getDefaultDb().moneyDao().insertMoney(
                    Money(
                        it.data.id,
                        100000f
                    )
                )

                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        }
        //观察登录失败的回调
        viewModel.loginFailed.observe(this) {
            Log.i("TagA", "e:$it")
        }
    }

    override fun initView() {
        dataBinding.toRegisterBtn.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_login

}